package com.slytherin.sns.spider.groovy


import com.slytherin.sns.spider.core.SlytherinScript;
import com.slytherin.sns.spider.page.Page;
import com.slytherin.sns.spider.result.Request;
import com.slytherin.sns.spider.result.down.Result

import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue;

public class CategoryScript implements SlytherinScript {

    BlockingQueue<Map.Entry<String, String>> queue = new LinkedBlockingQueue<>();
    @Override
    public Result process(Page page) {
        Request request = page.getRequest();
        Map<String, String> contextMap = request.getContextMap();
        String type = contextMap.get("type");
        Result result = new Result();
        switch (type){

            case "page1":
                result =context1(page,contextMap,result);
                break;
            case "page2":
                result =context2(page,contextMap,result);
                break;

        }
        return result;
    }

    private Result context1(Page page, Map<String, String> contextMap, Result result) {
        Result result1 = new Result();
        try {
            Map.Entry<String, String> message;
            while ((message = queue.poll()) != null) { // 阻塞直到队列中有消息
                System.out.println("Received: " + message.getKey() + " -> " + message.getValue());
                for (int i=0;i<5;i++){
                    String url = "https://geodata.ucdavis.edu/gadm/gadm4.1/json/gadm41_"+message.getKey()+"_"+i+".json";
                    Map<String, String> head = new HashMap<>();
                    head.put("accept-encoding","gzip, deflate, br");
                    head.put("accept-language","zh-CN,zh;q=0.9");
                    head.put("cache-control","max-age=0");
                    head.put("sec-ch-ua-mobile","?0");
                    head.put("user-agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36");
                    Request request = new Request(url).addHeader(head);
                    Map<String, String> urlContext = new HashMap<>();
                    urlContext.put("type","page2");
                    urlContext.put("fileName",message.getValue()+"_"+i + ".json");
                    urlContext.put("flodName",message.getValue());
                    request.addUrlContextMap(urlContext);


                    result1.addChildLinked(request)
                }
                // 处理消息...


            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.out.println("Consumption interrupted.");
        }

        return result1;
    }

    @Override
    Request seed(String seed) {
        getHashMap();
        String url = "https://www.dianping.com/shanghai/ch10/d1";
        Map<String, String> headersMap = new HashMap<>();
        headersMap.put("Host", "www.dianping.com");
        headersMap.put("Connection", "keep-alive");
        headersMap.put("sec-ch-ua", "\"Chromium\";v=\"128\", \"Not;A=Brand\";v=\"24\", \"Google Chrome\";v=\"128\"");
        headersMap.put("sec-ch-ua-mobile", "?0");
        headersMap.put("sec-ch-ua-platform", "\"macOS\"");
        headersMap.put("Upgrade-Insecure-Requests", "1");
        headersMap.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36");
        headersMap.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
        headersMap.put("Sec-Fetch-Site", "same-site");
        headersMap.put("Sec-Fetch-Mode", "navigate");
        headersMap.put("Sec-Fetch-User", "?1");
        headersMap.put("Sec-Fetch-Dest", "document");
        headersMap.put("Referer", "https://account.dianping.com/");
        headersMap.put("Accept-Encoding", "gzip, deflate, br, zstd");
        headersMap.put("Accept-Language", "zh-CN,zh;q=0.9");
        headersMap.put("Cookie", "_lxsdk_cuid=19363aa161fc8-09b452a9570a41-17525637-16a7f0-19363aa161fc8; _lxsdk=19363aa161fc8-09b452a9570a41-17525637-16a7f0-19363aa161fc8; _hc.v=b161327f-a769-8878-347c-a3adc40b6624.1732543912; fspop=test; logan_session_token=g290t4woldoufh358x4d; s_ViewType=10; WEBDFPID=8996y88269xw59140y52386zx39u549y80636zx5w32579585x40vyzv-2047904056714-1732544056208MCAYUGU75613c134b6a252faa6802015be905511619; qruuid=d27bb602-793c-4c71-bdc2-0aa3702ed9f8; dper=0202db1e9b6381e80309c7a0c1cb52ee424b81f1795c70dbc62df33331ca2e92b1036cea0f0c3a35ac3f0e0c5f912d50b4cc4fd1db5f5b474615000000009b2400007474d35337e5d020abeed114ed90cb139f76742604c07d4afe51281711da1363098ce8061e8bd671994c55b245ef9123; _lxsdk_s=19363aa161f-9d2-abd-c5b%7C%7C57");
        Request request = new Request(url).addHeader(headersMap);
        request.putContextMap("type","url1");
        Map<String, String> urlContext = new HashMap<>();
        urlContext.put("type","page1");
        request.addUrlContextMap(urlContext);
        return request;
    }

    public Map<String,String> getHashMap(){
        Map<String, String> countryMap = new HashMap<>();
        countryMap.put("AFG", "Afghanistan");
        countryMap.put("XAD", "Akrotiri and Dhekelia");
        countryMap.put("ALA", "Åland");
        countryMap.put("ALB", "Albania");
        countryMap.put("DZA", "Algeria");
        countryMap.put("ASM", "American Samoa");
        countryMap.put("AND", "Andorra");
        countryMap.put("AGO", "Angola");
        countryMap.put("AIA", "Anguilla");
        countryMap.put("ATA", "Antarctica");
        countryMap.put("ATG", "Antigua and Barbuda");
        countryMap.put("ARG", "Argentina");
        countryMap.put("ARM", "Armenia");
        countryMap.put("ABW", "Aruba");
        countryMap.put("AUS", "Australia");
        countryMap.put("AUT", "Austria");
        countryMap.put("AZE", "Azerbaijan");
        countryMap.put("BHS", "Bahamas");
        countryMap.put("BHR", "Bahrain");
        countryMap.put("BGD", "Bangladesh");
        countryMap.put("BRB", "Barbados");
        countryMap.put("BLR", "Belarus");
        countryMap.put("BEL", "Belgium");
        countryMap.put("BLZ", "Belize");
        countryMap.put("BEN", "Benin");
        countryMap.put("BMU", "Bermuda");
        countryMap.put("BTN", "Bhutan");
        countryMap.put("BOL", "Bolivia");
        countryMap.put("BES", "Bonaire, Saint Eustatius and Saba");
        countryMap.put("BIH", "Bosnia and Herzegovina");
        countryMap.put("BWA", "Botswana");
        countryMap.put("BVT", "Bouvet Island");
        countryMap.put("BRA", "Brazil");
        countryMap.put("IOT", "British Indian Ocean Territory");
        countryMap.put("VGB", "British Virgin Islands");
        countryMap.put("BRN", "Brunei");
        countryMap.put("BGR", "Bulgaria");
        countryMap.put("BFA", "Burkina Faso");
        countryMap.put("BDI", "Burundi");
        countryMap.put("CPV", "Cabo Verde");
        countryMap.put("KHM", "Cambodia");
        countryMap.put("CMR", "Cameroon");
        countryMap.put("CAN", "Canada");
        countryMap.put("XCA", "Caspian Sea");
        countryMap.put("CYM", "Cayman Islands");
        countryMap.put("CAF", "Central African Republic");
        countryMap.put("TCD", "Chad");
        countryMap.put("CHL", "Chile");
        countryMap.put("CHN", "China");
        countryMap.put("CXR", "Christmas Island");
        countryMap.put("XCL", "Clipperton Island");
        countryMap.put("CCK", "Cocos Islands");
        countryMap.put("COL", "Colombia");
        countryMap.put("COM", "Comoros");
        countryMap.put("COG", "Congo");
        countryMap.put("COK", "Cook Islands");
        countryMap.put("CRI", "Costa Rica");
        countryMap.put("CIV", "Côte d'Ivoire");
        countryMap.put("HRV", "Croatia");
        countryMap.put("CUB", "Cuba");
        countryMap.put("CUW", "Curaçao");
        countryMap.put("CYP", "Cyprus");
        countryMap.put("CZE", "Czech Republic");
        countryMap.put("COD", "Democratic Republic of the Congo");
        countryMap.put("DNK", "Denmark");
        countryMap.put("DJI", "Djibouti");
        countryMap.put("DMA", "Dominica");
        countryMap.put("DOM", "Dominican Republic");
        countryMap.put("TLS", "East Timor");
        countryMap.put("ECU", "Ecuador");
        countryMap.put("EGY", "Egypt");
        countryMap.put("SLV", "El Salvador");
        countryMap.put("GNQ", "Equatorial Guinea");
        countryMap.put("ERI", "Eritrea");
        countryMap.put("EST", "Estonia");
        countryMap.put("SWZ", "Eswatini");
        countryMap.put("ETH", "Ethiopia");
        countryMap.put("FLK", "Falkland Islands");
        countryMap.put("FRO", "Faroe Islands");
        countryMap.put("FJI", "Fiji");
        countryMap.put("FIN", "Finland");
        countryMap.put("FRA", "France");
        countryMap.put("GUF", "French Guiana");
        countryMap.put("PYF", "French Polynesia");
        countryMap.put("ATF", "French Southern Territories");
        countryMap.put("GAB", "Gabon");
        countryMap.put("GMB", "Gambia");
        countryMap.put("GEO", "Georgia");
        countryMap.put("DEU", "Germany");
        countryMap.put("GHA", "Ghana");
        countryMap.put("GIB", "Gibraltar");
        countryMap.put("GRC", "Greece");
        countryMap.put("GRL", "Greenland");
        countryMap.put("GRD", "Grenada");
        countryMap.put("GLP", "Guadeloupe");
        countryMap.put("GUM", "Guam");
        countryMap.put("GTM", "Guatemala");
        countryMap.put("GGY", "Guernsey");
        countryMap.put("GIN", "Guinea");
        countryMap.put("GNB", "Guinea-Bissau");
        countryMap.put("GUY", "Guyana");
        countryMap.put("HTI", "Haiti");
        countryMap.put("HMD", "Heard Island and McDonald Islands");
        countryMap.put("HND", "Honduras");
        countryMap.put("HUN", "Hungary");
        countryMap.put("ISL", "Iceland");
        countryMap.put("IND", "India");
        countryMap.put("IDN", "Indonesia");
        countryMap.put("IRN", "Iran");
        countryMap.put("IRQ", "Iraq");
        countryMap.put("IRL", "Ireland");
        countryMap.put("IMN", "Isle of Man");
        countryMap.put("ISR", "Israel");
        countryMap.put("ITA", "Italy");
        countryMap.put("JAM", "Jamaica");
        countryMap.put("JPN", "Japan");
        countryMap.put("JEY", "Jersey");
        countryMap.put("JOR", "Jordan");
        countryMap.put("KAZ", "Kazakhstan");
        countryMap.put("KEN", "Kenya");
        countryMap.put("KIR", "Kiribati");
        countryMap.put("XKO", "Kosovo");
        countryMap.put("KWT", "Kuwait");
        countryMap.put("KGZ", "Kyrgyzstan");
        countryMap.put("LAO", "Laos");
        countryMap.put("LVA", "Latvia");
        countryMap.put("LBN", "Lebanon");
        countryMap.put("LSO", "Lesotho");
        countryMap.put("LBR", "Liberia");
        countryMap.put("LBY", "Libya");
        countryMap.put("LIE", "Liechtenstein");
        countryMap.put("LTU", "Lithuania");
        countryMap.put("LUX", "Luxembourg");
        countryMap.put("MKD", "Macedonia");
        countryMap.put("MDG", "Madagascar");
        countryMap.put("MWI", "Malawi");
        countryMap.put("MYS", "Malaysia");
        countryMap.put("MDV", "Maldives");
        countryMap.put("MLI", "Mali");
        countryMap.put("MLT", "Malta");
        countryMap.put("MHL", "Marshall Islands");
        countryMap.put("MTQ", "Martinique");
        countryMap.put("MRT", "Mauritania");
        countryMap.put("MUS", "Mauritius");
        countryMap.put("MYT", "Mayotte");
        countryMap.put("MEX", "Mexico");
        countryMap.put("FSM", "Micronesia");
        countryMap.put("MDA", "Moldova");
        countryMap.put("MCO", "Monaco");
        countryMap.put("MNG", "Mongolia");
        countryMap.put("MNE", "Montenegro");
        countryMap.put("MSR", "Montserrat");
        countryMap.put("MAR", "Morocco");
        countryMap.put("MOZ", "Mozambique");
        countryMap.put("MMR", "Myanmar");
        countryMap.put("NAM", "Namibia");
        countryMap.put("NRU", "Nauru");
        countryMap.put("NPL", "Nepal");
        countryMap.put("NLD", "Netherlands");
        countryMap.put("NCL", "New Caledonia");
        countryMap.put("NZL", "New Zealand");
        countryMap.put("NIC", "Nicaragua");
        countryMap.put("NER", "Niger");
        countryMap.put("NGA", "Nigeria");
        countryMap.put("NIU", "Niue");
        countryMap.put("NFK", "Norfolk Island");
        countryMap.put("PRK", "North Korea");
        countryMap.put("ZNC", "Northern Cyprus");
        countryMap.put("MNP", "Northern Mariana Islands");
        countryMap.put("NOR", "Norway");
        countryMap.put("OMN", "Oman");
        countryMap.put("PAK", "Pakistan");
        countryMap.put("PLW", "Palau");
        countryMap.put("PSE", "Palestine");
        countryMap.put("PAN", "Panama");
        countryMap.put("PNG", "Papua New Guinea");
        countryMap.put("XPI", "Paracel Islands");
        countryMap.put("PRY", "Paraguay");
        countryMap.put("PER", "Peru");
        countryMap.put("PHL", "Philippines");
        countryMap.put("PCN", "Pitcairn Islands");
        countryMap.put("POL", "Poland");
        countryMap.put("PRT", "Portugal");
        countryMap.put("PRI", "Puerto Rico");
        countryMap.put("QAT", "Qatar");
        countryMap.put("REU", "Réunion");
        countryMap.put("ROU", "Romania");
        countryMap.put("RUS", "Russia");
        countryMap.put("RWA", "Rwanda");
        countryMap.put("BLM", "Saint-Barthélemy");
        countryMap.put("MAF", "Saint-Martin");
        countryMap.put("SHN", "Saint Helena");
        countryMap.put("KNA", "Saint Kitts and Nevis");
        countryMap.put("LCA", "Saint Lucia");
        countryMap.put("SPM", "Saint Pierre and Miquelon");
        countryMap.put("VCT", "Saint Vincent and the Grenadines");
        countryMap.put("WSM", "Samoa");
        countryMap.put("SMR", "San Marino");
        countryMap.put("STP", "São Tomé and Príncipe");
        countryMap.put("SAU", "Saudi Arabia");
        countryMap.put("SEN", "Senegal");
        countryMap.put("SRB", "Serbia");
        countryMap.put("SYC", "Seychelles");
        countryMap.put("SLE", "Sierra Leone");
        countryMap.put("SGP", "Singapore");
        countryMap.put("SXM", "Sint Maarten");
        countryMap.put("SVK", "Slovakia");
        countryMap.put("SVN", "Slovenia");
        countryMap.put("SLB", "Solomon Islands");
        countryMap.put("SOM", "Somalia");
        countryMap.put("ZAF", "South Africa");
        countryMap.put("SGS", "South Georgia and the South Sandwich Islands");
        countryMap.put("KOR", "South Korea");
        countryMap.put("SSD", "South Sudan");
        countryMap.put("ESP", "Spain");
        countryMap.put("XSP", "Spratly Islands");
        countryMap.put("LKA", "Sri Lanka");
        countryMap.put("SDN", "Sudan");
        countryMap.put("SUR", "Suriname");
        countryMap.put("SJM", "Svalbard and Jan Mayen");
        countryMap.put("SWE", "Sweden");
        countryMap.put("CHE", "Switzerland");
        countryMap.put("SYR", "Syria");
        countryMap.put("TWN", "Taiwan");
        countryMap.put("TJK", "Tajikistan");
        countryMap.put("TZA", "Tanzania");
        countryMap.put("THA", "Thailand");
        countryMap.put("TGO", "Togo");
        countryMap.put("TKL", "Tokelau");
        countryMap.put("TON", "Tonga");
        countryMap.put("TTO", "Trinidad and Tobago");
        countryMap.put("TUN", "Tunisia");
        countryMap.put("TUR", "Turkey");
        countryMap.put("TKM", "Turkmenistan");
        countryMap.put("TCA", "Turks and Caicos Islands");
        countryMap.put("TUV", "Tuvalu");
        countryMap.put("UGA", "Uganda");
        countryMap.put("UKR", "Ukraine");
        countryMap.put("ARE", "United Arab Emirates");
        countryMap.put("GBR", "United Kingdom");
        countryMap.put("USA", "United States");
        countryMap.put("UMI", "United States Minor Outlying Islands");
        countryMap.put("URY", "Uruguay");
        countryMap.put("UZB", "Uzbekistan");
        countryMap.put("VUT", "Vanuatu");
        countryMap.put("VAT", "Vatican City");
        countryMap.put("VEN", "Venezuela");
        countryMap.put("VNM", "Vietnam");
        countryMap.put("VIR", "Virgin Islands, U.S.");
        countryMap.put("WLF", "Wallis and Futuna");
        countryMap.put("ESH", "Western Sahara");
        countryMap.put("YEM", "Yemen");
        countryMap.put("ZMB", "Zambia");
        countryMap.put("ZWE", "Zimbabwe");

        for (Map.Entry<String, String> entry : countryMap.entrySet()) {
            queue.put(entry);
        }
        return countryMap;
    }

    Result context2(Page page, Map<String, String> stringStringMap, Result result) {
        println 111
        String directoryPath = "/Users/wanghan104/Desktop/weilantool/"+ stringStringMap.get("flodName") +"/"
        String fileName = stringStringMap.get("fileName")
        // String fileName = "output.json";
        String aa =page.getRawText()// 确保page.getJson()返回的是JSONObject对象

        try {
            // 创建文件路径
            Path path = Paths.get(directoryPath, fileName)

            // 确保目录存在，如果不存在则创建
            Files.createDirectories(path.getParent())

            // 将JSON数据写入文件
            Files.write(path, aa.getBytes(StandardCharsets.UTF_8))

            System.out.println("JSON data has been written to " + path.toString())
        } catch (IOException e) {
            e.printStackTrace()
        }

        result.addData(aa)
        return   result;
    }
}
